axios.defaults.baseURL = 'http://localhost';

new Vue({
  el: '#app',
  data() {
    //瓦片地图服务
    /*this._tileLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'http://t4.tianditu.com/DataServer?T=vec_w&tk=bdc01ebc2cfde2745d726baae3b672ad&x={x}&y={y}&l={z}'
      })
    });*/
    this._mapToken = void 0;
    this._map = void 0;   //地图实例
    this._routeLine = void 0;
    this._startMark = void 0;
    this._endMark = void 0;
    this._carMark = void 0;
    this._routeData = void 0;
    this._linePanel = void 0;
    this._startPointPanel = void 0;
    this._endPointPanel = void 0;
    return {
      timeRange: [],
      search: {
        headLicensePlateNo: '赣DM2089',   //车牌号
        plateColor: 2,   //车牌颜色
        startTime: '2024-09-28 00:00:00',
        endTime: '2024-09-29 23:59:59',
        timeType: 'real'
      },
      plateColors: [
        { label: '蓝色', value: 1 },
        { label: '黄色', value: 2 },
        { label: '黄绿色', value: 3 }
      ],
      loading: false
    }
  },
  created() {
    const urlData = getUrlData();
    if (urlData.timeType) this.search.timeType = urlData.timeType;
  },
  mounted() {
    getMapToken().then(res => {
      this._mapToken = res.data.data.access_token;

      var projection = new ol.proj.get("EPSG:4490");
      proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
      projection = new ol.proj.get('EPSG:4490');
      projection.setExtent([-180, -90, 180, 90]);
      
      var projectionExtent = projection.getExtent();
      var size = ol.extent.getWidth(projectionExtent) / 256;
      var resolutions = [];
      var matrixIds = [];
      for (var z = 0; z < 20; ++z) {
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = tileMatrixLabels + z;
      }
      var origin = ol.extent.getTopLeft(projectionExtent);

      this._tileLayer = new ol.layer.Tile({
        source: new ol.source.WMTS({
          name: "东莞地图",
          url: "http://ktd.dg:18080/data-slssldt?token=" + token,
          layer: "DG_BLUE_DIANZI_v4_1",
          style: '',
          matrixSet: "EPSG:4490_DG_BLUE_DIANZI_v4_1",
          format: "image/png",
          wrapX: true,
          tileGrid: new ol.tilegrid.WMTS({
            origin: origin,
            resolutions: resolutions,
            matrixIds: matrixIds,
          }),
        }),
      });

      this._map = new ol.Map({
        target: 'tdt-map',
        layers: [this._tileLayer],
        /*view: new ol.View({
          projection: 'EPSG:4326',    //坐标系
          center: [113.71945023536682, 23.022419214248657],
          zoom: 15,
          maxZoom: 19,
          minZoom: 10,
        }),*/
        view: new ol.View({
          center: [113.71945023536682, 23.022419214248657],
          projection: projection,
          zoom: 15,
          maxZoom: 19,
          minZoom: 10,
        }),
        controls: new ol.control.defaults({
          zoom: false
        })
      });
  
      //创建线段信息框
      this._linePanel = new Panel(this._map, {
        element: `线段信息框`
      });
  
      //创建起始点信息框
      this._startPointPanel = new Panel(this._map, {
        element: `起始点信息框`,
        closeBtn: true
      });
  
      //创建结束点信息框
      this._endPointPanel = new Panel(this._map, {
        element: `结束点信息框`,
        closeBtn: true
      });
  
      this._map.on('pointermove', e => {
        const pixel = this._map.getEventPixel(e.originalEvent);
        let _feature;
        const hit = this._map.forEachFeatureAtPixel(pixel, function (feature) {
          _feature = feature;
          return true; // 如果找到特征则返回true
        });
        if (hit) {
          const geom = _feature.getGeometry();
          const coordinate = this._map.getCoordinateFromPixel(pixel);
          //获取其是哪一条线段
          let index = getClosestPointIndexOnLine(geom, coordinate);
          if (index < 0) index = 0;
          if (index > this._routeData.length - 1) index = this._routeData.length - 1;
          const _routeData = this._routeData[index];
          if (!_routeData) return;
          this._linePanel.setPosition([_routeData.lon, _routeData.lat]);
          this._linePanel.updateContent(`${_routeData.gtm}`);
        } else {
          this._linePanel.setPosition(void 0);
        }
      });
    });
  },
  methods: {
    clear() {
      if (this._routeLine) this._map.removeLayer(this._routeLine);
      if (this._startMark) this._map.removeLayer(this._startMark);
      if (this._endMark) this._map.removeLayer(this._endMark);
      if (this._carMark) this._map.removeLayer(this._carMark);
    },
    serachBtnClick() {
      this.loading = true;
      this.clear();
      this._linePanel.setPosition(void 0);
      this._startPointPanel.setPosition(void 0);
      this._endPointPanel.setPosition(void 0);
      axios.post('/monitor/api/track/truckTrackQuery', this.search).then(res => {
        this.loading = false;
        if (!res.data.obj) {
          this.$message.warning(res.data.returnInfo);
          return;
        }

        if (!res.data.obj.runRoute || (res.data.obj.runRoute && res.data.obj.runRoute.length === 0)) {
          this.$message.warning('在该时间段车辆设备不在线');
          return;
        }

        res.data.obj.runRoute.forEach(item => {
          item.lon = parseFloat(item.lon);
          item.lat = parseFloat(item.lat);
        });

        this._routeData = res.data.obj.runRoute;

        const coordinates = res.data.obj.runRoute.map(route => [route.lon, route.lat]);
        //绘制路线
        const { line, feature } = drawLine(coordinates, {
          color: '#3AB602',
          width: 6
        });
        this._map.getView().fit(feature.getGeometry());
        this._map.addLayer(line);
        this._routeLine = line;

        //绘制起点
        {
          const { mark } = drawMark(coordinates[0], {
            src: '/assets/images/start-point.png',
            scale: .4
          });
          this._map.addLayer(mark);
          this._startMark = mark;

          console.log(coordinates[0]);

          setTimeout(() => {
            this._startPointPanel.setPosition(coordinates[0]);
            getAdressInfoByCoordinate(this._token, coordinates[0]).then(res => {
              if (res.data && res.data.list && res.data.list.length > 0) {
                const _data = res.data.list[0];
                this._startPointPanel.updateContent(`
                  <span>${_data.ADDRESS}</span>
                  <span>${this._routeData[0].gtm}</span>
                `);
              }
            });
          }, 200);
        }

        //绘制终点
        {
          const { mark } = drawMark(coordinates[coordinates.length - 1], {
            src: '/assets/images/end-point.png',
            scale: .4
          });
          this._map.addLayer(mark);
          this._endMark = mark;

          setTimeout(() => {
            this._endPointPanel.setPosition(coordinates[coordinates.length - 1]);
            getAdressInfoByCoordinate(this._token, coordinates[coordinates.length - 1]).then(res => {
              if (res.data && res.data.list && res.data.list.length > 0) {
                const _data = res.data.list[0];
                this._endPointPanel.updateContent(`
                  <span>${_data.ADDRESS}</span>
                  <span>${this._routeData[this._routeData.length - 1].gtm}</span>
                `);
              }
            });
          }, 200);
        }

        //绘制货车
        {
          const { mark } = drawMark(coordinates[coordinates.length - 1], {
            src: '/assets/images/car.png',
            scale: .4
          });
          this._map.addLayer(mark);
          this._carMark = mark;
        }
      });
    },
    timeRangeChange(value) {
      if (value) {
        this.search.startTime = formatDate(value[0]);
        this.search.endTime = formatDate(value[1]);
      } else {
        this.search.startTime = '';
        this.search.endTime = '';
      }
    }
  }
});